<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="120px">
                <el-form-item label="服务器URL" prop="name">
                    <el-input v-model="formData.url" placeholder="请输入服务器URL" clearable />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" placeholder="请输入备注" clearable />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import Popup from '@/components/popup/index.vue'
import type { FormInstance } from 'element-plus'
import { editHost,getHostInfo,addHost } from '@/api/application/gzh/index'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑接入' : '新增接入'
})
const route = useRoute()
const formData = reactive({
    url:"",
    wechat_id:route.query.id,
    remark:""
})
const id = ref(0)
const handleClose = () => {
    emit('close')
}
const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await editHost({...formData,id:id.value}) : await addHost({...formData})
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}
const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    id.value = row.id
    const data = await getHostInfo({
        id: row.id
    })
    setFormData(data)
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
